package com.witmore.skyline.web.service.third.tplink;

import javax.xml.bind.DatatypeConverter;
import java.util.TreeMap;
import java.util.UUID;

import static com.witmore.skyline.web.service.third.constants.ApiTpLinkClientConstant.*;
import static com.witmore.skyline.web.service.third.tplink.ApiTPClient.*;

public class AuthorizationDemo {




    public static void main(String[] args) throws Exception {

//        ApiTPClient.authorizationReady()



        // ************* 步骤 1：准备签名计算相关参数 *************
        String timestamp = String.valueOf(System.currentTimeMillis() / 1000);
        String nonce = UUID.randomUUID().toString().replaceAll("-", "");
        // 请求路径，根据具体接口进行替换
        String path = "/vms/open/webServer/v1/requestStreamUrl";
        // 请求体内容，此处为示例，实际使用时替换为需要发送请求的请求体
        String payload = "{\"qrCode\": \"F9CF0261334E6140B\",\"channelId\":1,\"clientType\":\"chrome 99.0\",\"streamType\":\"video\",\"resolution\":2}";

        // ************* 步骤 2：拼接待签名字符串 *************
        String hashedCanonicalRequest = sha256Hex(payload);
        System.out.println(hashedCanonicalRequest);
        String credentialScope = METHOD_POST + " " + path + " " + "tp-link_request";
        String stringToSign = ALGORITHM + "\n" + timestamp + "\n" + credentialScope + "\n" + hashedCanonicalRequest;
        System.out.println(stringToSign);

        // ************* 步骤 3：计算签名 *************
        byte[] secretDate = hmac256(SK.getBytes(UTF8), timestamp);
        byte[] secretService = hmac256(secretDate, path);
        byte[] secretSigning = hmac256(secretService, "tp-link");
        String signature = DatatypeConverter.printHexBinary(hmac256(secretSigning, stringToSign)).toLowerCase();
        System.out.println(signature);

        // ************* 步骤 4：拼接 Authorization *************
        String authorization = "Timestamp=" + timestamp + "," + "Nonce=" + nonce + "," + "AccessKey=" + AK + "," +
                "Signature=" + signature + "," + "TerminalId=" + TERMINAL_ID;
        System.out.println(authorization);

        TreeMap<String, String> headers = new TreeMap<>();
        headers.put("X-Authorization", authorization);
        headers.put("Content-Type", CT_JSON);
        headers.put("Host", HOST);

        String string = sendPost("https://" + HOST + path, payload, headers);
        System.out.println("1.4.5.3获取音视频流访问地址 : "+string);
    }
}